<template>
  <div id="app">
    <el-dialog :close-on-click-modal="false" :visible.sync="addReimburseDialog" :title="title"
               width="40%"
               top="50px"
               center
               @closed="loading=false"
    >
      <div class="flexBox">
        <p><span>*</span>店铺名称：</p>
        <el-select filterable remote :remote-method="remoteMethod" value-key="orderId"
                   clearable v-model="orderId" size='small'
                   :disabled="disabled"
                   style="width:300px" placeholder="请输入店铺名称">
          <el-option v-for="item in saleNameList" :key="item.orderId" :label="item.storeName" :value="item.orderId">
          </el-option>
        </el-select>
      </div>
      <div class="flexBox">
        <p><span>*</span>报销金额：</p>
        <el-input v-model="money" size="small"></el-input>
      </div>
      <div class="flexBox">
        <p><span>*</span>报销类型：</p>
        <el-select clearable v-model="levelId" size='small'
                   @change="changeType"
                   filterable

                   style="width:300px" placeholder="请选择">
          <el-option v-for="item in type" :key="item.levelId" :label="item.levelName" :value="item.levelId">
          </el-option>
        </el-select>
      </div>
      <div class="flexBox">
        <p><span>*</span>承担主体：</p>
        <el-select clearable v-model="optioner" size='small'
                   filterable
                   style="width:300px" placeholder="请选择">
          <el-option v-for="item in SaleTypeData" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="flexBox">
        <p>收款方式：</p>
        <el-radio-group v-model="paymentMethod" v-removeAriaHidden>
          <el-radio :label="1">银行卡</el-radio>
          <el-radio :label="2">微信、支付宝</el-radio>
        </el-radio-group>
      </div>
      <div
          style="border: 1px solid #82848a;width: 420px;padding-top: 20px;padding-right:40px;padding-bottom: 10px;margin-bottom: 15px;margin-left: 30px"
          v-if="paymentMethod==1">
        <div class="flexBox">
          <p>户名：</p>
          <el-input v-model="cardName" size="small"></el-input>
        </div>
        <div class="flexBox">
          <p>卡号：</p>
          <el-input v-model="cardNo" size="small"></el-input>
        </div>
        <div class="flexBox">
          <p>开户行：</p>
          <el-input v-model="bankName" size="small"></el-input>
        </div>
      </div>
      <div v-if="paymentMethod==2" style="display: flex;margin-bottom: 15px;margin-left: 200px">
        <el-upload
            class="upload-demo"
            :multiple="false"
            :on-change="handleChangePic"
            list-type="picture"
            :headers="headerToken"
            :on-success="onSuccess"
            :action="`${$apiHost}/common/fileImgUrl`">
          <i class="el-icon-upload" style="color: #66b1ff"></i>
          <div class="el-upload__text" style="color: #66b1ff"><em>点击上传二维码图片</em></div>
        </el-upload>
        <el-image style="width: 50px; height: 50px"
                  v-if="disabled&&payUrl"
                  ref="preview" :src="host+payUrl" :preview-src-list="[host+payUrl]">
        </el-image>
      </div>
      <div style="display: flex;align-items: center;margin-bottom: 20px;margin-left: 28px" id="photos">
        <div style="width:120px;text-align: center;margin-top: 30px">
          <span style="color: red;">*</span>报销凭证：
        </div>
        <div>
          <span style="color:gray;font-size: 12px;">(粘贴复制即可上传图片)</span>
          <div class="div" style="display: flex;align-items: center;width: 500px;flex-wrap: wrap">

            <div v-for='(v, i) in proof' style="display: flex;align-items: center;margin-right: 10px;">
              <el-image :key="i" style="width: 50px; height: 50px"
                        ref="preview" :src="host+v" :preview-src-list="[host + v]">
              </el-image>
              <div @click="deletePic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="flexBox">
        <p><span>*</span>费用说明：</p>
        <el-input v-model="matter" type="textarea" size="small" style="width: 300px"></el-input>
      </div>
      <div class="flexBox">
        <p>备注：</p>
        <el-input v-model="remark" type="textarea" size="small" style="width: 300px"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addReimburseDialog = false">取 消</el-button>
    <el-button type="primary" @click="addInfo('add')" :loading="loading" v-if="!disabled">确 定</el-button>
    <el-button type="primary" @click="addInfo('edit')" :loading="loading" v-if="disabled">修 改</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import store from "../../../store";

export default {
  name: "addReimburse",
  data() {
    return {
      preSalesImg: [],
      addReimburseDialog: false,
      storeName: "",
      host: this.$imgHost,
      typeText: "",
      disabled:false,
      paymentMethod: "",
      saleNameList: [],
      fileList: [],
      preSalesImgList: [],
      productImgs: [],
      bankName: "",
      title: "",
      orderIdReal: "",
      financeId: "",
      levelId: "",
      matter: "",
      remark: "",
      cardNo: "",
      cardName: "",
      paymentType: "",
      orderId: "",
      money: "",
      optioner: "",
      proof: [],
      SaleTypeData: [],
      payUrl: [],
      options: [],
      addStatus: "",
      type: [],
      loading: false,
    }
  },
  computed: {
    headerToken() {
      const token = store.state.token
      return {
        token,
      };
    },
    headers() {
      const token = store.state.token
      return {
        token,
      };
    },
  },
  created() {
    document.addEventListener('paste', this.handlePaste)
    this.getTypeList()
  },
  methods: {
    deletePic(i) {
      this.proof.splice(i, 1)
    },
    getTypeList() {
      this.$api.newAfterSaleTypesEnum().then(res => {
        this.SaleTypeData = res
      })
    },
    handlePaste(event) {
      if (!this.addReimburseDialog) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else if (item.kind === 'string' && item.type.startsWith('text/')) {
            console.log("text")
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      if (imageFile.size > 5000000) return this.$message.warning('图片大于5MB，请压缩后上传！')
      axios.post(`${this.$apiHost}/common/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': store.state.token
        }
      })
          .then(response => {
            this.proof.push(response.data.result[0]);
            // this.preSalesImgList.push('https://' + response.data.result[0]);
          })
          .catch(error => {
          });
    },
    handleChangePic(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
        this.payUrl=fileList
        console.log(this.payUrl)
      }
    },
    handleOpen(data) {
      if (data) {
        this.title='编辑'
        this.disabled = true
        this.orderId = data.orderName,
            this.orderIdReal=data.orderId,
            this.money = data.money,
            this.storeLedgerId=data.id,
            this.financeId = data.financeId,
            this.financeLevelId = data.financeLevelId,
            this.levelId = data.financeLevelId,
            this.payUrl = data.payUrl,
            this.proof = data.proof,
            this.cardNo = data.cardNo,
            this.cardName = data.cardName,
            this.optioner = data.optioner.toString(),
            this.bankName = data.bankName,
            this.matter = data.matter,
            this.remark = data.remark,
            this.paymentMethod = data.paymentMethod
      } else {
        this.disabled =false
        this.title='新增'
        this.orderId = "",
            this.money = "",
            this.financeId = "",
            this.financeLevelId = "",
            this.levelId = "",
            this.payUrl = "",
            this.proof = [],
            this.cardNo = "",
            this.cardName = "",
            this.optioner = "",
            this.bankName = "",
            this.matter = "",
            this.remark = "",
            this.paymentMethod = ""
      }
      this.addReimburseDialog = true
      this.getType()
    },
    async getType() {
      const res = await this.$api.storeLedgerGetFinanceLevelTypeDto()
      this.type = res
    },
    remoteMethod(val) {
      if (val) {
        const params = {
          storeName: val,
          isClose: 1
        }
        this.$api.orderGetOrderInfoLikeName(params).then(res => {
          this.saleNameList = res
        })
      }
    },
    onSuccess(res) {
      const {productImgs = []} = this;
      if (res.code == 200 && res.result) {
        this.payUrl = res.result[0];
        console.log(this.payUrl)
      }
    },
    addInfo(val) {
      if (this.loading) return
      if (this.paymentMethod == 1) {
        this.payUrl = ""
      } else if (this.paymentMethod == 2 || this.payType == 3) {
        this.cardNo = ""
        this.cardName = ""
        this.bankName = ""
      }
      if (!this.orderId) {
        return this.$message.warning("请输入店铺名称!")
      }
      if (!this.money) {
        return this.$message.warning("请输入报销金额!")
      }
      if (!this.financeId) {
        return this.$message.warning("请选择报销分类!")
      }
      if (!this.optioner) {
        return this.$message.warning("请选择承担主体!")
      }

      // if (!this.paymentMethod) {
      //   return this.$message.warning("请选择付款方式!")
      // }
      // if (this.paymentMethod == 1 && (!this.cardNo || !this.cardName || !this.bankName)) {
      //   return this.$message.warning("请完善银行卡信息!")
      // }
      if (!this.proof.length) {
        return this.$message.warning("请上传报销凭证!")
      }
      // if (!this.matter) {
      //   return this.$message.warning("请填入报销费用说明!")
      // }
      // if (this.paymentMethod != 1 && !this.payUrl) {
      //   return this.$message.warning("请上传微信或支付宝付款码!")
      // }
      const data = {
        orderId: this.orderId,
        money: this.money,
        financeId: this.financeId,
        financeLevelId: this.financeLevelId,
        payUrl: this.payUrl.toString() || "",
        proof: this.proof || "",
        cardNo: this.cardNo,
        optioner: this.optioner,
        cardName: this.cardName,
        bankName: this.bankName,
        matter: this.matter,
        remark: this.remark,
        paymentMethod: this.paymentMethod
      }
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, 7000)
      if(val=='add'){
        this.$api.storeLedgerAddStoreLedgerDetails(data).then(res => {
          if (res == 1) {
            this.$message.success("新增成功!")
            this.$emit('addStatus', 1);
            this.addReimburseDialog = false
          }
        })
      }else if(this.financeId==1&&val!='add'){
        data.status=4
        data.storeLedgerId=this.storeLedgerId
        data.orderId=this.orderIdReal
        this.$api.storeLedgerUpdateStoreLedgerDetails(data).then(res => {
          if (res == 1) {
            this.$message.success("修改成功!")
            this.$emit('addStatus', 2);
            this.addReimburseDialog = false
          }
        })
      } else {
        data.storeLedgerId=this.storeLedgerId
        data.orderId=this.orderIdReal
        data.status=0
        this.$api.storeLedgerUpdateStoreLedgerDetails(data).then(res => {
          if (res == 1) {
            this.$message.success("修改成功!")
            this.$emit('addStatus', 2);
            this.addReimburseDialog = false
          }
        })
      }

    },
    changeType(val) {
      this.$api.storeLedgerGetFinanceLevelTypeDto().then(res => {
        const result = res.find(item => item.levelId === val);
        this.financeId = result.financeId
        this.financeLevelId = result.levelId
      })
    },
  }
}
</script>

<style scoped lang="less">
.flexBox {
  display: flex;
  margin-left: 50px;
  margin-bottom: 15px;
  justify-content: flex-start;
  align-items: center;

  p {
    width: 100px;
  }

  span {
    color: #ce0e0f;
  }

  .el-input {
    width: 300px;
  }
}
</style>